<template>
  <div class="code_message">
    <div style="display: flex; align-items: center; gap: 5px">
      <h4 class="title">商品信息</h4>
      <HPlainButton :height="22" :padding-lr="6" @click="onAddGoodClick">新建商品</HPlainButton>
    </div>
    <div class="table-code">
      <el-table :border="true" stripe resizable :data="tableData" style="width: 100%" height="320px">
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column label="序号" width="70" fixed>
          <template v-slot="scope">
            <span class="order"> {{ scope.$index + 1 }} </span>
            <span class="add_delete">
              <el-icon size="16" class="add" @click="onClickEditProductDialog(scope.row.type)">
                <EditPen />
              </el-icon>
              <el-icon color="rgba(245, 108, 108, 1)" size="16" @click="detelePro(scope.$index, scope.row)">
                <Delete />
              </el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="一物一码" prop="code" show-overflow-tooltip width="150">
          <template v-slot="i">
            {{ i.row.code ? i.row.code : '临时编码' }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="140" prop="goodsBrand" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="商品" width="140" prop="goodsName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="规格" width="140" prop="goodsSpecName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="数量" prop="qty" min-width="60">
          <template v-slot="item">
            <el-input v-if="item.row.type == 3" v-model="item.row.qty" @change="inputChange"
              @input="item.row.qty = item.row.qty.replace(/[^0-9]/g, '')" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="图片" width="60">
          <template v-slot="item">
            <div class="pic" v-if="item.row.image">
              <el-image :preview-src-list="[item.row.image]" style="width: 30px; height: 30px" :src="item.row.image"
                fit="contain" :preview-teleported="true">
                <template #error>
                  <div class="image-slot">
                    <el-icon size="28" color="#999">
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="登记日期" width="200" prop="buyTime" show-overflow-tooltip>
          <template v-slot="item">
            <el-date-picker v-if="item.row.type != 1" class="date-scle" value-format="YYYY-MM-DD"
              v-model="item.row.buyTime" type="date" />
          </template>
        </el-table-column>
        <el-table-column label="登记信息" min-width="300" show-overflow-tooltip>
          <template v-slot="item">
            <div>
              {{ item.row.name }}&nbsp;{{ item.row.phone }}&nbsp; {{ item.row.province }}-{{
        item.row.city
      }}-{{ item.row.area }}-{{ item.row.town }}-{{ item.row.address }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 选择商品弹窗 -->
  <el-drawer v-model="productDialog" title="选择商品" size="76%" :close-on-click-modal="false"
    :close-on-press-escape="false" append-to-body>
    <div class="code-dialog">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleTabChange">
        <!-- 商品列表 -->
        <el-tab-pane label="商品列表" name="third" style="height: 100%">
          <el-container>
            <el-aside width="220px">
              <div class="main_left">
                <h4 class="titile_h4">商品类型</h4>
                <ul class="ul_pop_up" v-loading="loading" element-loading-text="加载中...">
                  <li class="li_pop_up" :style="{ color: itemIndex == null ? '#007cff' : '' }"
                    @click="onClickItem(null)">
                    全部
                  </li>
                  <li class="li_pop_up" :style="{ color: itemIndex == item.id ? '#007cff' : '' }"
                    @click="onClickItem(item.id)" v-for="(item, index) in dataType" :key="index">
                    {{ item.name }}
                  </li>
                </ul>
                <div class="page_pages">
                  <el-pagination hide-on-single-page :small="true" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-size="pageSize" :total="total"
                    layout="total, prev, pager, next" />
                </div>
              </div>
            </el-aside>
            <el-main>
              <div class="main_right" v-loading="loading2" element-loading-text="加载中...">
                <div class="header" style="
                    display: flex;
                    align-items: center;
                    gap: 5px;
                    margin-bottom: 12px;
                    justify-content: flex-end;
                  ">
                  <el-select style="width: 140px" v-model="brandId" placeholder="请选择品牌" filterable clearable
                    reserve-keyword remote-show-suffix :fit-input-width="true" :loading="brandLoading"
                    :filter-method="searchBrandSelect" :popper-append-to-body="false" @change="getOrderGoods"
                    :collapse-tags="true" :max-collapse-tags="2" :collapse-tags-tooltip="true">
                    <el-option v-for="item in brandOptions" :label="item.name" :key="item.id" :value="item.id">
                      <el-tooltip v-if="item.name.length > 20" :content="item.name" effect="dark" placement="top">
                        <span>{{ item.name }}</span>
                      </el-tooltip>
                    </el-option>
                  </el-select>
                  <el-input clearable v-model="input" placeholder="商品型号/商品名称/商品规格" @keyup.enter="getOrderGoods"
                    @clear="getOrderGoods" style="width: 200px" />
                  <HButton type="primary" @click="getOrderGoods">
                    <el-icon>
                      <Search />
                    </el-icon>
                    搜索
                  </HButton>
                  <HButton style="margin: 0" @click="onResetGoodListFilter">
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                    重置
                  </HButton>
                </div>
                <div class="table-reg">
                  <el-table :border="true" stripe resizable :data="goodstableData"
                    @select-all="selectAllgoodsinformation" ref="multipleTableRef3"
                    @select="handleClickgoodsinformation" @row-click="rowClick3" max-height="580">
                    <template #empty>
                      <el-empty description="暂无数据" />
                    </template>
                    <el-table-column show-overflow-tooltip type="selection" width="40" fixed />
                    <el-table-column show-overflow-tooltip prop="code" label="商品编号" />
                    <el-table-column show-overflow-tooltip prop="brand" label="品牌" />
                    <el-table-column show-overflow-tooltip prop="name" label="名称" />
                    <el-table-column show-overflow-tooltip prop="model" label="型号" />
                    <el-table-column show-overflow-tooltip prop="specName" label="规格" />
                    <el-table-column show-overflow-tooltip label="图片">
                      <template v-slot="item">
                        <div class="pic" v-if="item.row.image">
                          <el-image style="width: 30px; height: 30px" :src="item.row.image" fit="contain"
                            @click="lookPic(item.row.image)">
                            <template #error>
                              <div class="image-slot">
                                <el-icon size="28" color="#999">
                                  <Picture />
                                </el-icon>
                              </div>
                            </template>
                          </el-image>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip prop="warrantyDay" width="100">
                      <template #header>
                        <div style="white-space: nowrap">质保时间(天)</div>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="footer" style="margin-top: 12px; justify-content: flex-end; display: flex">
                    <Pagination ref="pagination3" :list_total="typeTotal3" @size-change="getOrderGoods"
                      @current-change="getOrderGoods" />
                  </div>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-tab-pane>

        <!-- 客户商品 -->
        <el-tab-pane label="客户商品" name="first" v-loading="loadingUser2" element-loading-text="加载中..."
          style="height: 100%">
          <div class="header mar_r" style="
              display: flex;
              align-items: center;
              gap: 5px;
              justify-content: flex-end;
              margin-right: 0;
            ">
            <el-input style="width: 120px" v-model="inputUsercode" placeholder="输入登记编码"
              @keyup.enter="getRegisterCodeUser" @clear="getRegisterCodeUser"  clearable />
            <el-input v-model="inputUsermodel" placeholder="输入商品型号" style="width: 120px"
              @keyup.enter="getRegisterCodeUser" @clear="getRegisterCodeUser" clearable />
            <HButton type="primary" @click="getRegisterCodeUser">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton style="margin: 0" @click="clearVlaue2">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
          <div style="margin: 12px 0">
            <el-table :border="true" stripe resizable :data="UsergoodstableData" @selectAll="selectAllUserSelec"
              @select="handleClickSelec" max-height="580" ref="multipleTableRef1" @row-click="rowClick1">
              <template #empty>
                <el-empty description="暂无数据" :image-size="140" />
              </template>
              <el-table-column show-overflow-tooltip type="selection" width="40" fixed />
              <el-table-column show-overflow-tooltip prop="goodsSpecName" label="规格" width="140" />
              <el-table-column show-overflow-tooltip prop="code" label="一物一码" width="140" />
              <el-table-column show-overflow-tooltip prop="goodsBrand" label="品牌" width="120" />
              <el-table-column show-overflow-tooltip prop="goodsName" label="名称" width="120" />
              <el-table-column show-overflow-tooltip prop="goodsModel" label="型号" width="120" />
              <el-table-column show-overflow-tooltip prop="goodsType" label="类型" width="140" />
              <el-table-column show-overflow-tooltip label="地址" width="180">
                <template v-slot="item">
                  <div v-html="` ${item.row.province}   ${item.row.city}  ${item.row.area}  ${item.row.town}  ${item.row.address}`
        ">
                  </div>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip prop="warrantyDay" label="质保时间(天)" width="140" />
              <el-table-column show-overflow-tooltip prop="warrantyStartTime" label="质保开始" width="140" />
              <el-table-column show-overflow-tooltip prop="warrantyEndTime" label="质保截止" width="140" />
            </el-table>
            <div class="footer" style="display: flex; justify-content: flex-end; margin-top: 12px">
              <Pagination ref="pagination1" :list_total="typeTotal" @size-change="getRegisterCodeUser"
                @current-change="getRegisterCodeUser" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 未登记商品 -->
        <el-tab-pane label="未登记商品" name="second" v-loading="loading3" element-loading-text="加载中..."
          style="height: 100%">
          <div class="header mar_r" style="
              display: flex;
              align-items: center;
              gap: 5px;
              justify-content: flex-end;
              margin-right: 0;
            ">
            <el-input style="width: 120px" @clear="getNotRegisterGoodsCode" v-model="inputUnCode" placeholder="输入登记编码" clearable
              @keyup.enter="getNotRegisterGoodsCode" />
            <el-input v-model="inputUnModel" placeholder="输入商品型号" style="width: 120px" clearable
              @keyup.enter="getNotRegisterGoodsCode" @clear="getNotRegisterGoodsCode"/>
            <HButton type="primary" @click="getNotRegisterGoodsCode">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton style="margin: 0" @click="clearVlaue">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
          <div style="margin: 12px 0">
            <el-table :border="true" stripe resizable :data="unregisteredtableData" @selectAll="selectAllunregistered"
              ref="multipleTableRef2" @select="handleClickunregistered" max-height="580" @row-click="rowClick2">
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column show-overflow-tooltip type="selection" width="40" fixed />
              <el-table-column show-overflow-tooltip prop="goodsSpecName" label="规格" />
              <el-table-column show-overflow-tooltip prop="code" label="一物一码" />
              <el-table-column show-overflow-tooltip prop="goodsBrand" label="品牌" />
              <el-table-column show-overflow-tooltip prop="goodsName" label="名称" />
              <el-table-column show-overflow-tooltip prop="goodsModel" label="型号" />
              <el-table-column show-overflow-tooltip prop="goodsType" label="类型" />
              <el-table-column show-overflow-tooltip prop="warrantyDay" label="质保时间(天)" />
            </el-table>
            <div style="display: flex; justify-content: flex-end; margin-top: 12px">
              <Pagination ref="pagination2" :list_total="typeTotal2" @size-change="getNotRegisterGoodsCode"
                @current-change="getNotRegisterGoodsCode" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div style="display: flex; gap: 10px; justify-content: flex-end">
        <HButton isModal type="primary" @click="onCommit">确定</HButton>
        <HButton isModal @click="onCacel">取消</HButton>
      </div>
    </template>
  </el-drawer>

  <HModal v-model="dialogVisible" title="查看图片">
    <img :src="lookImgUrl" style="width: 100%" alt="" />
  </HModal>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ref, watch, toRefs, nextTick } from 'vue'
import { Delete, Search, Picture, RefreshRight, EditPen } from '@element-plus/icons-vue'
import { ElMessage, TabPaneName } from 'element-plus'
import { getOrderProduct } from '@/api/order'
import { getNotRegisterCode, getRegisterCode } from '@/api/code'
import { typePageSelect, brandPageSelect } from '@/api/goodsInfo'
import { ElTable } from 'element-plus'
import _ from 'lodash'
import HPlainButton from '@/components/common/button/HPlainButton.vue'
import HButton from '@/components/common/button/HButton.vue'
import HModal from '@/components/common/Modal/HModal.vue'

const props = defineProps({
  userPerson: String,
  orderGoodsList: Array || Object,
  factoryId: String,
})

// 解构props
const { userPerson, orderGoodsList, factoryId } = toRefs(props)

const emit = defineEmits<{
  (e: 'get-order-goods-vos', value: Array<any>): void
}>()

/**
 * 商品列表重置点击事件
 */
const onResetGoodListFilter = async () => {
  input.value = ''
  brandId.value = null
  await getOrderGoods()
}

const productDialog = ref(false)
const loading = ref(false)
const loading2 = ref(false)
const loading3 = ref(false)
const loadingUser2 = ref(false)
const input = ref('')
const inputUnCode = ref('') //输入未登记编码搜索
const inputUnModel = ref('') //输入未登记型号搜索
const total = ref(0)
const typeTotal = ref(0)
const typeTotal2 = ref(0)
const typeTotal3 = ref(0)
const pageSize = ref(15)
const activeName = ref('third')
const currentPage = ref(1)
const dataType = ref(null)
const goodstableData = ref([])
const UsergoodstableData = ref([]) //用户商品
const pagination1 = ref()
const pagination2 = ref()
const pagination3 = ref()
const brandLoading = ref(false)
const unregisteredtableData = ref([]) //未登记商品
const inputUsercode = ref('') //用户商品编号搜索
const inputUsermodel = ref('') //用户商品型号搜索
const brandVal = ref()
const orderGoodsTypes = ref([])
const orderGoodsVos1 = ref([]) //选择客户商品
const orderGoodsVos2 = ref([]) //选择未登记商品
const orderGoodsVos3 = ref([]) //选择商品信息
const tableData = ref([]) //确定后的商品列表
const multipleTableRef1 = ref<InstanceType<typeof ElTable>>()
const multipleTableRef2 = ref<InstanceType<typeof ElTable>>()
const multipleTableRef3 = ref<InstanceType<typeof ElTable>>()
// 搜索框下拉数据
const brandOptions = ref([])
const brandId = ref(null) // 品牌ID
// 查看图片
const dialogVisible = ref(false)
const lookImgUrl = ref(null)
const lookPic = (img) => {
  lookImgUrl.value = img
  dialogVisible.value = true
}
// 选择客户商品
const handleClickSelec = (val, row) => {
  let item = {
    ...row,
    type: 1,
    qty: 1,
    codeIds: [row.id],
    id: null,
    buyTime: row.warrantyStartTime,
  }
  let result = val.some((item) => item.code == row.code) //判断是否是 选中
  if (result) {
    orderGoodsVos1.value.push(item)
  } else {
    orderGoodsVos1.value = orderGoodsVos1.value.filter((o) => o.code != row.code)
  }
}
// 客户商品列表勾选 全选
const selectAllUserSelec = (val) => {
  if (val.length > 0) {
    val.map((row) => {
      let result = orderGoodsVos1.value.some((o) => row.code == o.code)
      let item = {
        ...row,
        type: 1,
        qty: 1,
        codeIds: [row.id],
        id: null,
        buyTime: row.warrantyStartTime,
      }
      if (!result) {
        orderGoodsVos1.value.push(item)
      }
    })
  } else if (val.length == 0) {
    UsergoodstableData.value.map((row) => {
      orderGoodsVos1.value = orderGoodsVos1.value.filter((o) => o.code != row.code)
    })
  }
}
// 选择未登记商品
const handleClickunregistered = (val, row) => {
  let item = { ...row, type: 2, qty: 1, codeIds: [row.id], id: null, buyTime: '' }
  let result = val.some((item) => item.id == row.id) //判断是否是 选中
  if (result) {
    orderGoodsVos2.value.push(item)
  } else {
    orderGoodsVos2.value = orderGoodsVos2.value.filter((o) => o.codeIds[0] != row.id)
  }
}
// 未登记商品列表勾选 全选
const selectAllunregistered = (val) => {
  if (val.length > 0) {
    val.map((row) => {
      let result = orderGoodsVos2.value.some((o) => row.id == o.codeIds[0])
      let item = { ...row, type: 2, qty: 1, codeIds: [row.id], id: null, buyTime: '' }
      if (!result) {
        orderGoodsVos2.value.push(item)
      }
    })
  } else if (val.length == 0) {
    unregisteredtableData.value.map((row) => {
      orderGoodsVos2.value = orderGoodsVos2.value.filter((o) => o.codeIds[0] != row.id)
    })
  }
}
// 选择商品信息
const handleClickgoodsinformation = (val, row) => {
  let item = {
    image: row.image,
    id: null,
    goodsId: row.id,
    goodsBrand: row.brand,
    goodsModel: row.model,
    goodsName: row.name,
    goodsSpecId: row.specId,
    goodsSpecName: row.specName,
    goodsType: row.type,
    qty: 1,
    warrantyDay: row.warrantyDay,
    type: 3,
    buyTime: '',
  }
  let result = val.some((item) => item.specId == row.specId) //判断是否是 选中
  if (result) {
    orderGoodsVos3.value.push(item)
  } else {
    orderGoodsVos3.value = orderGoodsVos3.value.filter((o) => o.goodsSpecId != row.specId)
  }
}

// 商品信息列表勾选 全选
const selectAllgoodsinformation = (val) => {
  if (val.length > 0) {
    val.map((row) => {
      let result = orderGoodsVos3.value.some((o) => row.specId == o.goodsSpecId)
      let item = {
        image: row.image,
        id: null,
        goodsId: row.id,
        goodsBrand: row.brand,
        goodsModel: row.model,
        goodsName: row.name,
        goodsSpecId: row.specId,
        goodsSpecName: row.specName,
        goodsType: row.type,
        qty: 1,
        warrantyDay: row.warrantyDay,
        type: 3,
        buyTime: '',
      }
      if (!result) {
        orderGoodsVos3.value.push(item)
      }
    })
  } else if (val.length == 0) {
    let tmp = []
    tmp = goodstableData.value.map((row) => {
      return row.specId
    })
    orderGoodsVos3.value = orderGoodsVos3.value.filter((o) => !tmp.includes(o.goodsSpecId))
  }
}
// 单击选中商品
const rowClick3 = (item) => {
  if (orderGoodsVos3.value.some(o => o.goodsSpecId == item.specId)) return
  handleClickgoodsinformation([item], item)
  multipleTableRef3.value!.toggleRowSelection(item, true)
}
const rowClick2 = (item) => {
  if (orderGoodsVos2.value.some(o => o.codeIds[0] == item.id)) return
  handleClickunregistered([item], item)
  multipleTableRef2.value!.toggleRowSelection(item, true)
}
const rowClick1 = (item) => {
  if (orderGoodsVos1.value.some(o => o.code == item.code)) return
  handleClickSelec([item], item)
  multipleTableRef1.value!.toggleRowSelection(item, true)
}

/**
 * 添加商品按钮点击事件
 */
const onAddGoodClick = async () => {
  productDialog.value = true // 打开弹窗
  await getTypeData()
  await getBrandOptions(brandId.value)
  await getOrderGoods()
}

// 点击修改商品信息
const onClickEditProductDialog = (n) => {
  productDialog.value = true
  switch (n) {
    case 1:
      handleTabChange('first')
      break
    case 2:
      handleTabChange('second')
      break
    case 3:
      handleTabChange('third')
      break
  }
}
//重新渲染
const goEditProductDialog = async (n) => {
  // 点击打开 添加商品 获取已添加的渲染回显
  if (orderGoodsList.value.length > 0) {
    orderGoodsList.value.filter((o) => {
      if (o.type == 1 && o.orderGoodsVos.length > 0) {
        orderGoodsVos1.value = o.orderGoodsVos
      }
      if (o.type == 2 && o.orderGoodsVos.length > 0) {
        orderGoodsVos2.value = o.orderGoodsVos
      }
      if (o.type == 3 && o.orderGoodsVos.length > 0) {
        orderGoodsVos3.value = o.orderGoodsVos
      }
    })
  }

  switch (n) {
    case 1:
      // 重新渲染 客户商品选择
      activeName.value = 'first'
      orderGoodsVos1.value.map((goods) => {
        UsergoodstableData.value.find((item) => {
          if (item.code === goods.code) {
            nextTick(() => {
              multipleTableRef1.value!.toggleRowSelection(item, undefined)
            })
          }
        })
      })
      break
    case 2:
      // // 重新渲染 未登记商品选择
      activeName.value = 'second'
      orderGoodsVos2.value.map((goods) => {
        unregisteredtableData.value.find((item) => {
          if (item.id === goods.codeIds[0]) {
            nextTick(() => {
              multipleTableRef2.value!.toggleRowSelection(item, undefined)
            })
          }
        })
      })
      break
    case 3:
      // // 重新渲染 商品信息选择
      activeName.value = 'third'
      orderGoodsVos3.value.map((goods) => {
        goodstableData.value.find((item) => {
          if (item.specId === goods.goodsSpecId) {
            nextTick(() => {
              multipleTableRef3.value!.toggleRowSelection(item, undefined)
            })
          }
        })
      })
      break
  }
}
// 初始化 ===>>重置未登记商品搜索
const clearVlaue = () => {
  inputUnCode.value = ''
  inputUnModel.value = ''
  getNotRegisterGoodsCode()
}
// 初始化 ===>>重置客户商品搜索
const clearVlaue2 = () => {
  inputUsercode.value = ''
  inputUsermodel.value = ''
  getRegisterCodeUser()
}
// input输入数量变化
const inputChange = (n) => {
  orderGoodsVos1.value = []
  orderGoodsVos2.value = []
  orderGoodsVos3.value = []
  orderGoodsTypes.value = []
  tableData.value.filter((o) => {
    switch (o.type) {
      case 1:
        orderGoodsVos1.value.push(o)
        break
      case 2:
        orderGoodsVos2.value.push(o)
        break
      case 3:
        orderGoodsVos3.value.push(o)
        break
    }
  })

  if (orderGoodsVos1.value.length > 0) {
    orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos1.value, type: 1 })
  }
  if (orderGoodsVos2.value.length > 0) {
    orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos2.value, type: 2 })
  }
  if (orderGoodsVos3.value.length > 0) {
    orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos3.value, type: 3 })
  }
  emit('get-order-goods-vos', orderGoodsTypes.value)
}
const itemIndex = ref(null)
const goodsTypeId = ref('') // 商品分类ID
// 点击商品类型
const onClickItem = (val) => {
  itemIndex.value = val
  goodsTypeId.value = val
  getOrderGoods()
}
// 切换商品
const handleTabChange = (name: TabPaneName) => {
  switch (name) {
    case 'first':
      if (!userPerson.value) {
        ElMessage({
          message: '请先选择客户信息！',
          type: 'warning',
          offset: 250,
        })
      } else {
        nextTick(async () => {
          await getRegisterCodeUser()
        })
      }
      break
    case 'second':
      nextTick(() => {
        getNotRegisterGoodsCode()
      })
      break
    case 'third':
      getTypeData()
      getBrandOptions(brandId.value)
      nextTick(() => {
        getOrderGoods()
      })
      break
  }
}
// 获取商品类型
const getTypeData = async () => {
  loading.value = true
  const data = {
    limit: pageSize.value,
    name: '',
    page: currentPage.value,
  }
  const res = await typePageSelect(data)
  dataType.value = res.data.data.rows
  total.value = Number(res.data.data.total)
  loading.value = false
}

/**
 * 获取品牌下拉数据
 * @param name
 */
const getBrandOptions = async (name) => {
  const data = {
    limit: 0,
    name: name,
    page: 0,
  }
  const res = await brandPageSelect(data)
  brandOptions.value = res.data.data.rows
}
// current-page 改变时触发
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getTypeData()
}

/**
 * 搜索品牌下拉数据
 */
const searchBrandSelect = _.throttle((query: string) => {
  brandVal.value = query
  if (query) {
    brandLoading.value = true
    setTimeout(async () => {
      brandLoading.value = false
    }, 1000)
  }
}, 500)

/**
 * 删除产品
 * @param i
 * @param row
 */
const detelePro = (i, row) => {
  orderGoodsTypes.value = orderGoodsList.value
  tableData.value = tableData.value.filter((o, index) => {
    return index != i
  })
  orderGoodsTypes.value = orderGoodsTypes.value.filter((o) => {
    if (o.type == row.type && o.type == 1) {
      o.orderGoodsVos = o.orderGoodsVos.filter((item) => item.goodsSpecId !== row.goodsSpecId)
      if (o.orderGoodsVos.length == 0) {
        return !o
      }
    }
    if (o.type == row.type && o.type == 2) {
      o.orderGoodsVos = o.orderGoodsVos.filter((item) => item.code !== row.code)
      if (o.orderGoodsVos.length == 0) {
        return !o
      }
    }
    if (o.type == row.type && o.type == 3) {
      o.orderGoodsVos = o.orderGoodsVos.filter((item) => item.goodsSpecId !== row.goodsSpecId)
      if (o.orderGoodsVos.length == 0) {
        return !o
      }
    }
    return o
  })
  emit('get-order-goods-vos', orderGoodsTypes.value)
}

/**
 * 获取商品列表
 */
const getRegisterCodeUser = async () => {
  const data = {
    brandId: null,
    code: inputUsercode.value,
    model: inputUsermodel.value,
    limit: pagination1.value.size,
    page: pagination1.value.current,
    typeId: null,
  }
  loadingUser2.value = true
  const res = await getRegisterCode(data, userPerson.value)
  if (res.data.success) {
    UsergoodstableData.value = res.data.data.rows
    typeTotal.value = Number(res.data.data.total)
    //  重新渲染 客户商品选择
    await goEditProductDialog(1)
  }
  loadingUser2.value = false
}

/**
 * 获取未登记商品编号
 */
const getNotRegisterGoodsCode = async () => {
  const data = {
    brandId: null,
    code: inputUnCode.value,
    model: inputUnModel.value,
    limit: pagination2.value.size,
    page: pagination2.value.current,
    typeId: null,
    factoryId: factoryId.value ? factoryId.value : null,
  }
  loading3.value = true
  const res = await getNotRegisterCode(data)
  if (res.data.success) {
    unregisteredtableData.value = res.data.data.rows
    typeTotal2.value = Number(res.data.data.total)
    // 重新渲染 未登记商品选择
    await goEditProductDialog(2)
  }
  loading3.value = false
}

/**
 * 获取商品信息列表
 */
const getOrderGoods = async () => {
  loading2.value = true
  const data = {
    brandId: brandId.value,
    keyword: input.value,
    limit: 50,
    page: 1,
    typeId: goodsTypeId.value,
    factoryId: factoryId.value ? factoryId.value : null,
  }
  if (pagination3.value) {
    data.limit = pagination3.value.size
    data.page = pagination3.value.current
  }
  const res = await getOrderProduct(data)
  loading2.value = false
  if (res.data.success) {
    goodstableData.value = res.data.data.rows
    typeTotal3.value = Number(res.data.data.total)
    // 重新渲染 商品信息选择 type==3
    await goEditProductDialog(3)
  }
}

/**
 * 取消
 */
const onCacel = () => {
  productDialog.value = false
  orderGoodsTypes.value = []
  activeName.value = 'third'
  orderGoodsVos1.value = []
  orderGoodsVos2.value = []
  orderGoodsVos3.value = []
}

// 确定 选择的商品
const onCommit = () => {
  orderGoodsTypes.value = _.cloneDeep(orderGoodsList.value)

  // 工单编码商品类型type：1-客户已登记商品，2-未登记商品，3-商品信息,示例值(1)
  if (orderGoodsTypes.value.length > 0) {
    let isgoodsTrue1 = orderGoodsTypes.value.some((o) => o.type == 1)
    let isgoodsTrue2 = orderGoodsTypes.value.some((o) => o.type == 2)
    let isgoodsTrue3 = orderGoodsTypes.value.some((o) => o.type == 3)

    // 客户已登记商品
    if (orderGoodsVos1.value.length > 0) {
      if (isgoodsTrue1) {
        let arr = []
        let arr2 = []
        orderGoodsTypes.value = orderGoodsTypes.value.map((o) => {
          if (o.type == 1) {
            orderGoodsVos1.value.filter((goods) => {
              const matchingObj = o.orderGoodsVos.some((item) => item.code == goods.code)
              o.orderGoodsVos.filter((item) => {
                if (item.code == goods.code) {
                  arr.push(item)
                }
              })
              if (!matchingObj) {
                arr2.push(goods)
              }
            })
            o.orderGoodsVos = [...arr, ...arr2]
          }
          return o
        })
      } else {
        orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos1.value, type: 1 })
      }
    } else {
      orderGoodsTypes.value = orderGoodsTypes.value.filter(o => o.type != 1)
    }
    // 未登记商品
    if (orderGoodsVos2.value.length > 0) {
      if (isgoodsTrue2) {
        orderGoodsTypes.value = orderGoodsTypes.value.map((o) => {
          if (o.type == 2) {
            o.orderGoodsVos = orderGoodsVos2.value
          }
          return o
        })
      } else {
        orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos2.value, type: 2 })
      }
    } else {
      orderGoodsTypes.value = orderGoodsTypes.value.filter(o => o.type != 2)
    }
    // 商品信息
    if (orderGoodsVos3.value.length > 0) {
      if (isgoodsTrue3) {
        let arr = []
        let arr2 = []
        orderGoodsTypes.value = orderGoodsTypes.value.map((o) => {
          if (o.type == 3) {
            orderGoodsVos3.value.filter((goods) => {
              const matchingObj = o.orderGoodsVos.some(
                (item) => item.goodsSpecId == goods.goodsSpecId,
              )
              o.orderGoodsVos.filter((item) => {
                if (item.goodsSpecId == goods.goodsSpecId) {
                  arr.push(item)
                }
              })
              if (!matchingObj) {
                arr2.push(goods)
              }
            })
            o.orderGoodsVos = [...arr, ...arr2]
          }
          return o
        })
      } else {
        orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos3.value, type: 3 })
      }
    } else {
      orderGoodsTypes.value = orderGoodsTypes.value.filter(o => o.type != 3)
    }
  } else {
    if (orderGoodsVos1.value.length > 0) {
      orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos1.value, type: 1 })
    }
    if (orderGoodsVos2.value.length > 0) {
      orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos2.value, type: 2 })
    }
    if (orderGoodsVos3.value.length > 0) {
      orderGoodsTypes.value.push({ orderGoodsVos: orderGoodsVos3.value, type: 3 })
    }
  }
  tableData.value = []
  orderGoodsTypes.value.filter((o) => {
    tableData.value.push(...o.orderGoodsVos)
  })

  orderGoodsVos1.value = []
  orderGoodsVos2.value = []
  orderGoodsVos3.value = []
  emit('get-order-goods-vos', orderGoodsTypes.value)
  productDialog.value = false
  activeName.value = 'third'
}

// 监听用户是否改变
watch(
  () => userPerson.value,
  () => {
    tableData.value = []
    emit('get-order-goods-vos', [])
  },
)

// 监听下拉数据变化时是否进行搜索
watch(
  () => brandVal.value,
  (newVal) => {
    if (newVal != '') {
      getBrandOptions(newVal)
    } else {
      getBrandOptions('')
    }
  },
)
const setDate = (d) => {
  const date = new Date(d)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}
const setTable = () => {
  tableData.value = []
  orderGoodsList.value.forEach((o) => {
    o.orderGoodsVos.buyTime = setDate(o.orderGoodsVos.buyTime)
    o.orderGoodsVos.endTime = setDate(o.orderGoodsVos.endTime)
    tableData.value.push(...o.orderGoodsVos)
  })
}
defineExpose({
  setTable
})
</script>

<style scoped lang="scss">
@import '../index';
</style>
